//
//  API.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/11/18.
//

import Foundation
import HandyJSON

enum UserRole: String {
    case Engineer = "gongRole"  // 工程师
//    case Admin = "admin"   // 超级管理员
//    case Normal = "common" // 普通用户角色
    case HeadOffice = "zongRole" // 总行
    case BranchOffice = "fenRole" // 分行
    case SubBranchOffice = "zhiRole" // 支行
    case Lattice = "wangRole" // 网点
    case SecurityGuard = "baoRole" // 保安
    case Cleaning = "cleaning_role" // 保洁
}

let stringKey = "192006250b4c09247ec02edce69f6a2d";

class API {
    class func getSign<T: Encodable>(param: T) -> DefaultParam {
        let timestamp = Int(Date().timeIntervalSince1970)
        let encoder = JSONEncoder()
        do {
            let jsonData = try encoder.encode(param)
            let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: [])
            if var jsonDictionary = jsonObject as? [String: Any] {
                jsonDictionary["timestamp"] = timestamp
                let sortedKeys = jsonDictionary.keys.sorted()
                var stringA = ""
                for key in sortedKeys {
                    if let value = jsonDictionary[key], "\(value)" != "" {
                        stringA += "\(key)=\(value)&"
                    }
                }
//                print("stringA", "\(stringA)key=\(stringKey)")
                let signature = "\(stringA)key=\(stringKey)".md5?.uppercased()
//                print("signature", signature)
                let param = DefaultParam(timestamp: "\(timestamp)", signature: signature)
                return param
            }
        } catch {
            print(error)
        }
                       
        let sign = "timestamp=\(timestamp)".md5
        let _param = DefaultParam(timestamp: "\(timestamp)", signature: sign)
        return _param
    }
    
    class func getSign() -> DefaultParam {
        let timestamp = Int(Date().timeIntervalSince1970)
        let sign = "timestamp=\(timestamp)&key=\(stringKey)".md5
//        print("stringA", "timestamp=\(timestamp)&key=\(stringKey)")
//        print("sign", sign)
        let _param = DefaultParam(timestamp: "\(timestamp)", signature: sign)
        return _param
    }
}

/// 电子台账提交
/// 维修工程师修复 &  新增报修单评价 & 保存报修单列表
/// 签到/签退接口
/// 巡检结果
struct CommonJsonParam: Encodable {
    var jsonStr: String?
    var data: String?
    
    var timestamp: String?
    var signature: String?
    
    init(jsonStr: String? = nil, data: String? = nil) {
        self.jsonStr = jsonStr
        self.data = data
    }
}

// MARK: - 系统通用
let URLCaptchaImage = "/common/captchaImage"
let URLConvert = "/common/coordinate/convert"
let URLAppVersion = "/getAppVersionByIos" // 获取app版本信息

struct SettingParam: Encodable {
    var lngLat: String?
    var timestamp: String?
    var signature: String?
    
    init(lngLat: String? = nil) {
        self.lngLat = lngLat
    }
}

extension API {
    /// 图形验证码
    class func getCaptchaImage(withBlock block: ResponseBlock<RespModal>?) {
        let signP = getSign()
        NetManager.request(url: URLCaptchaImage, method: .get, parameters: signP, modelType: RespModal.self, resultBlock: block)
    }
    
    /// 坐标转换
    class func getConvert(withParam _param: SettingParam, block: ResponseBlock<LocModal>?) {
        let signP = getSign(param: _param)
        var param = _param
        param.timestamp = signP.timestamp
        param.signature = signP.signature
        NetManager.request(url: URLConvert, method: .get, parameters: param, modelType: LocModal.self, resultBlock: block)
    }
    
    /// 获取app版本信息
    class func getAppVersion(withBlock block: ResponseBlock<AppVersionModal>?) {
        let signP = getSign()
        NetManager.request(url: URLAppVersion, method: .get, parameters: signP, modelType: AppVersionModal.self, resultBlock: block)
    }
}

// MARK: - 获取部门
let URLDeptList = "/dept/list" // 部门列表
let URLDeptTree = "/dept/tree" // 部门树列表

struct DeptParam: Encodable {
    var deptName: String?
    var timestamp: String?
    var signature: String?
    
    init(deptName: String? = nil) {
        self.deptName = deptName
    }
}

extension API {
    // 部门列表✅已对接
    class func getDeptList(withBlock block: ResponseBlock<DeptModal>?) {
        let signP = getSign()
        NetManager.request(url: URLDeptList, method: .get, parameters: signP, modelType: DeptModal.self, resultBlock: block)
    }
    
    // 部门树列表✅已对接
    class func getDeptTree(withParam param: DeptParam? = DeptParam(), block: ResponseBlock<DeptTreeModal>?) {
        let signP = getSign(param: param)
        var _param = param
        _param?.timestamp = signP.timestamp
        _param?.signature = signP.signature
        NetManager.request(url: URLDeptTree, method: .get, parameters: _param, modelType: DeptTreeModal.self, resultBlock: block)
    }
}

// MARK: - 入口-找回密码
let URLRetrievepwdPtsm = "/retrievepwd/ptsm"   /// 平台个人信息保护声名
let URLRetrievepwdReset = "/retrievepwd/reset" /// 重置密码
let URLRetrievepwdSend = "/retrievepwd/send"   /// 发送验证码

struct RetrievepwdSendParam: Encodable {
    var code: String?
    var username: String?
    var uuid: String?
    
    var timestamp: String?
    var signature: String?
}

extension API {
    /// 平台个人信息保护声名✅已对接
    class func getRetrievepwdPtsm(withBlock block: ResponseBlock<MarkdownModal>?) {
        let signP = getSign()
        NetManager.request(url: URLRetrievepwdPtsm, method: .get, parameters: signP, modelType: MarkdownModal.self, resultBlock: block)
    }
    
    /// 重置密码
    class func postRetrievepwdReset(withParam param: LoginParam, block: ResponseBlock<LoginRespModal>?) {
//        let signP = getSign(param: _param)
//        var param = _param
//        param.timestamp = signP.timestamp
//        param.signature = signP.signature
        
        var _param = LoginParam()
        _param.code = param.code
        
        let password = try? AESEncyptUtil.encryptCBC(encryptText: param.password ?? "", key: secreKey, ivs: iv)
        _param.password = password
        _param.username = param.username
        _param.uuid = param.uuid
        
        let signP = getSign(param: _param)
        _param.timestamp = signP.timestamp
        _param.signature = signP.signature        
        
        NetManager.request(url: URLRetrievepwdReset, parameters: _param, modelType: LoginRespModal.self, resultBlock: block)
    }
    
    /// 发送验证码
    class func postRetrievepwdSend(withParam _param: RetrievepwdSendParam, block: ResponseBlock<LoginRespModal>?) {
        let signP = getSign(param: _param)
        var param = _param
        param.timestamp = signP.timestamp
        param.signature = signP.signature
        NetManager.request(url: URLRetrievepwdSend, parameters: param, modelType: LoginRespModal.self, resultBlock: block)
    }
}

// MARK: - 个人信息

let URLProfileInitedit = "/profile/initedit"   /// 修改初始数据
let URLProfileUpdatePwd = "/profile/updatePwd" /// 修改密码

struct ProfileParam: Encodable {
    var deptId: String?
    var nickname: String?
    var newPassword: String?
    var oldPassword: String?
    
    var timestamp: String?
    var signature: String?
}

extension API {
    /// 修改初始数据
    class func postProfileInitedit(withParam _param: ProfileParam, block: ResponseBlock<RespModal>?) {
        let signP = getSign(param: _param)
        var param = _param
        param.timestamp = signP.timestamp
        param.signature = signP.signature
        NetManager.request(url: URLProfileInitedit, parameters: param, modelType: RespModal.self, resultBlock: block)
    }
    
    /// 修改密码
    class func postProfileUpdatePwd(withParam _param: ProfileParam, block: ResponseBlock<RespModal>?) {
        let signP = getSign(param: _param)
        var param = _param
        param.timestamp = signP.timestamp
        param.signature = signP.signature
        NetManager.request(url: URLProfileUpdatePwd, parameters: param, modelType: RespModal.self, resultBlock: block)
    }
}

// MARK: - 通知

let URLNoticeList = "/notice/list"   /// 公告通知列表
let URLNoticeDetail = "/notice" /// 公告通知详情
let URLNoticeOwner = "/v2/notice/owner" /// 获取消息通知

struct NoticeParam: Encodable {
    var noticeType: String? // 1通知 2公告 3系统消息
    
    var timestamp: String?
    var signature: String?
    init(noticeType: String? = nil) {
        self.noticeType = noticeType
    }
}

extension API {
    /// 公告通知列表
    class func getNoticeList(withParam _param: NoticeParam, block: ResponseBlock<NoticeModal>?) {
        let signP = getSign(param: _param)
        var param = _param
        param.timestamp = signP.timestamp
        param.signature = signP.signature
        NetManager.request(url: URLNoticeList, method: .get, parameters: param, modelType: NoticeModal.self, resultBlock: block)
    }
    
    /// 公告通知详情
    class func getNoticeDetail(withId id: Int64, block: ResponseBlock<NoticeModal>?) {
        let param = getSign()
        NetManager.request(url: "\(URLNoticeDetail)/\(id)", method: .get, parameters: param, modelType: NoticeModal.self, resultBlock: block)
    }
    
    /// 公告通知详情
    class func getNoticeOwner(withBlock block: ResponseBlock<NoticeOwnerModal>?) {
        let param = getSign()
        NetManager.request(url: URLNoticeOwner, method: .get, parameters: param, modelType: NoticeOwnerModal.self, resultBlock: block)
    }
}

// MARK: - Modals

// 默认字典
struct LabelDictModal: HandyJSON {
    var type: String?
    var dictLabel: String?
    var dictValue: String?
}

struct LocModal: HandyJSON {
    var location: String?
}

struct MarkdownModal: HandyJSON {
    var name: String?
    var nr: String?
}

// 用户信息
struct UserModal: HandyJSON {
    var nickName: String?
    var sex: String?
    var deptId: Int64?
    var userName: String?
    var userId: Int64?
    var avatar: String?
    var dept: DeptModal?
}

// 部门列表
struct DeptModal: HandyJSON {
    var deptId: Int64?
    var deptName: String?
    var orderNum: Int64?
    var phone: String?
    var leader: String?
    var email: String?
    var deptPosition: String?
    var parentName: String?
    var parentId: Int64?
    var indexNum: Int64 = 0
    var sfxz: Bool?
    var sfyy: Bool?
    var color: UIColor = .randomLightColor
    var isWd: Bool?
}

// 部门树列表
struct DeptTreeModal: HandyJSON {
    var id: Int64?
    var pid: Int64?
    var index: Int64?
    var label: String?
    var disabled: Bool?
    var isDisabled: Bool?
    var wdzrr: String?
    var wdzrrhm: String?
    var wdPosition: String?
    var sfxz: Bool?
    var sfyy: Bool?
    var children: [DeptTreeModal]?
    var expanded: Bool = true
}

// 公告通知列表
struct NoticeModal: HandyJSON {
    var userId: String?
    var status: String?
    var mklxdm: String?
    var noticeContent: String?
    var noticeType: String?
    var mkywcj: String?
    var noticeId: Int64?
    var mkywid: Int64?
    var noticeTitle: String?
    var remark: String?
    var createTime: String?
    var createBy: String?
}

// 获取app版本信息
struct AppVersionModal: HandyJSON {
    var versionCode: Int64? // 版本号
    var versionName: String? // 版本名称
    var sfqzgx: Int64? // 强制更新 0 是 1 否
    var url: String? // 下载地址
    var id: Int64?
}

struct NoticeOwnerModal: HandyJSON {
    var status: Int64?
    var info: NoticeOwnerInfoModal?
}

struct NoticeOwnerInfoModal: HandyJSON {
    var noticeId: Int64? // 消息ID
    var noticeTitle: String?  // 标题
    var noticeType: String?  // 类型 1通知 2公告 3系统消息 4系统通知
    var noticeContent: String?  // 内容（没有HTML 标签）
    var mklxdm: String?  // 模块类型代码 1.报警通知、2履职管理、3维保服务、4智慧内保、5一键报修、6台账管理、7检查监督、8智慧保安
    var mkywcj: String?  // 业务场景 1列表 2详情
    var mkywid: String?  // 业务关联ID
}
